package cn.dankal.flyaudio.friend;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.util.SimpleTextChange;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.basiclib.widget.ClearEditText;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.adapter.GroupListAdapter;
import cn.dankal.flyaudio.adapter.GroupListAdapter2;
import cn.dankal.flyaudio.friend.utils.DialogCreator;
import cn.dankal.flyaudio.friend.utils.HandleResponseCode;
import cn.dankal.flyaudio.friend.utils.pinyin.HanziToPinyin;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetGroupIDListCallback;
import cn.jpush.im.android.api.callback.GetGroupInfoCallback;
import cn.jpush.im.android.api.model.GroupInfo;
import cn.jpush.im.android.api.model.UserInfo;

/**
 * Created by ${chenyn} on 2017/4/26.
 */

public class GroupActivity extends BaseActivity {

    //    private ListView mGroupList;
    private GroupListAdapter2 mGroupListAdapter;
    private RecyclerView mGorupList;
    private Context mContext;
    private boolean isFromForward = false;
    private boolean isBusinessCard = false;
    private String mUserName;
    private String mAppKey;
    private String mAvatarPath;
    protected int mWidth;
    private TextView searchTextView;

    private ClearEditText searchEditText;

    private MultipleStatusView statusView;

    private List<GroupInfo> groupInfos = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_group;
    }

    @Override
    protected void initComponents() {
        addSingleTitleBar("群聊");
        this.mContext = this;
        DisplayMetrics dm = new DisplayMetrics();
        mWidth = dm.widthPixels;
//        mGroupList = (ListView) findViewById(R.id.group_list);
        //待发送名片的参数
        mGorupList = findViewById(R.id.recyclerview);
        mUserName = getIntent().getStringExtra("userName");
        mAppKey = getIntent().getStringExtra("appKey");
        mAvatarPath = getIntent().getStringExtra("avatar");
        mGorupList.setLayoutManager(new LinearLayoutManager(this));
        mGroupListAdapter = new GroupListAdapter2();
        mGorupList.setAdapter(mGroupListAdapter);
        initData();
        initSearch();
    }


    private void initData() {
        final Dialog dialog = DialogCreator.createLoadingDialog(this, "加载中");
        dialog.show();
        final List<GroupInfo> infoList = new ArrayList<>();
        JMessageClient.getGroupIDList(new GetGroupIDListCallback() {
            @Override
            public void gotResult(int responseCode, String responseMessage, final List<Long> groupIDList) {
                if (responseCode == 0) {
                    final int[] groupSize = {groupIDList.size()};
                    if (groupIDList.size() > 0) {
                        for (Long id : groupIDList) {
                            JMessageClient.getGroupInfo(id, new GetGroupInfoCallback() {
                                @Override
                                public void gotResult(int i, String s, GroupInfo groupInfo) {
                                    if (i == 0) {
                                        groupSize[0] = groupSize[0] - 1;
                                        infoList.add(groupInfo);
                                        if (groupSize[0] == 0) {
                                            setAdapter(infoList, dialog);
                                        }

                                    }
                                }
                            });
                        }
                    } else {
                        dialog.dismiss();
                        ToastUtils.showShort("您还没有群组");
                    }
                } else {
                    dialog.dismiss();
                    HandleResponseCode.onHandle(mContext, responseCode, false);
                }
            }
        });
    }

    private void initSearch() {
        statusView = findViewById(R.id.multiple_status_view);
        searchTextView = findViewById(R.id.tv_search);
        searchEditText = findViewById(R.id.et_search);
        searchEditText.setOnSearchListener(new ClearEditText.OnSearchListener() {
            @Override
            public void doSearch(String keyword) {
                if (TextUtils.isEmpty(keyword)) return;
                doSearchMethod(keyword);
            }
        });
        searchTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String key = searchEditText.getText().toString();
                if (TextUtils.isEmpty(key)) return;
                doSearchMethod(key);
            }
        });
        searchEditText.addTextChangedListener(new SimpleTextChange() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                super.onTextChanged(s, start, before, count);
                if (TextUtils.isEmpty(s)) {
                    mGroupListAdapter.addDatas(groupInfos, true);
                    statusView.showContent();
                    findViewById(R.id.status_hint_content_1).setVisibility(View.VISIBLE);
                    TextView tvContent  = findViewById(R.id.status_hint_content_1);
                    tvContent.setText("- "+groupInfos.size()+"个群聊-");
                }
            }
        });
        statusView.showContent();
    }

    private void doSearchMethod(String key) {
        List<GroupInfo> searResult = new ArrayList<>();
        for (GroupInfo userInfo : groupInfos) {
            ArrayList<HanziToPinyin.Token> tokens = HanziToPinyin.getInstance()
                    .get(userInfo.getGroupName());
            StringBuilder sb = new StringBuilder();
            if (tokens != null && tokens.size() > 0) {
                for (HanziToPinyin.Token token : tokens) {
                    if (token.type == HanziToPinyin.Token.PINYIN) {
                        sb.append(token.target);
                    } else {
                        sb.append(token.source);
                    }
                }
            }
            if (sb.toString().contains(key) || userInfo.getGroupName().contains(key)) {
                searResult.add(userInfo);
            }
        }
        if (searResult.isEmpty()) {
            statusView.showEmpty("- 没有找到“搜索”相关群聊 -");
            findViewById(R.id.status_hint_content_1).setVisibility(View.INVISIBLE);
        }else {
            mGroupListAdapter.addDatas(searResult,true);
            statusView.showContent();
            findViewById(R.id.status_hint_content_1).setVisibility(View.VISIBLE);
            TextView tvContent  = findViewById(R.id.status_hint_content_1);
            tvContent.setText("- "+searResult.size()+"个群聊-");

        }
    }


    public void setAdapter(List<GroupInfo> infoList, Dialog dialog) {
        dialog.dismiss();
        //来自转发时flag是1
        if (getIntent().getFlags() == 1) {
            isFromForward = true;
        }
        //来自名片的请求设置flag==2
        if (getIntent().getFlags() == 2) {
            isBusinessCard = true;
        }
        mGroupListAdapter.initParams(isFromForward, mWidth, isBusinessCard, mUserName, mAppKey, mAvatarPath);
        mGroupListAdapter.addDatas(infoList, true);
        groupInfos.addAll(infoList);
        findViewById(R.id.status_hint_content_1).setVisibility(View.VISIBLE);
        TextView tvContent  = findViewById(R.id.status_hint_content_1);
        tvContent.setText("- "+groupInfos.size()+"个群聊-");
    }

    @Override
    protected void onResume() {
        super.onResume();
        //刷新气泡
        if(mGroupListAdapter != null)
            mGroupListAdapter.notifyDataSetChanged();
    }
}
